package com.songlin.testv2ex.android_gson_json;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by 松林 on 2015/10/4.
 */
public class HttpUtils {

    public  HttpUtils() {
    }

    public static String getJsonContent(String url_path) {
        try {
            URL url = new URL(url_path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            int code = httpURLConnection.getResponseCode();
            if ( code == 200 ) {
                return changeInputStream(httpURLConnection.getInputStream());
            }
        } catch (Exception ex) {
            System.out.println("Catch Exception From GetJsonContent()");
        }
                return "";
    }

    private static String changeInputStream(InputStream inputStream) {
        String jsonString = "";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        try {
            //InputStream的read(Byte[] data)方法，在read了byte数据时返回非负值，内容被outputStream通过write()保存了
            //当读完了内容时，循环终止，若有Exception就跳到catch
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data,0,len);
            }
            jsonString = new String(outputStream.toByteArray());
        } catch(Exception ex) {
            Log.d("Throws Exception", "From \"private static String changeInputStream(InputStream inputStream) \" in Topic.java");
            ex.printStackTrace();
        }
        return jsonString;
    }
}
